/*
描述：问题发布视图组件，提供问题发布表单和标签选择功能
完成人：何艺珲
完成时间: 2025/04/26
*/
<script setup lang="ts">

import HeaderComponent from "@/components/HomeView/HeaderComponent.vue";
import { ref, onMounted } from 'vue';
import axios from "axios";
import { ElMessage } from 'element-plus';
import router from "@/router";
const token = localStorage.getItem('token')
const userid = localStorage.getItem('id')
const title = ref('');
const content = ref('');
const url = ref('');
const tagList = ref<Array<{id: number, tagname: string, content: string}>>([]);
const selectedTags = ref<Array<number>>([]);

const result = ref<
    {
      code: number;
      msg: string;
      data: number | null;
    }
>();

// 获取标签列表
const getTagList = async (): Promise<void> => {
  try {
    const response = await axios.request({
      method: 'GET',
      url: 'http://localhost:8089/tag/getTagList',
      headers: {
        Accept: '*/*',
        'Content-Type': 'application/json'
      }
    });

    if (response.data.code === 1) {
      tagList.value = response.data.data;
    } else {
      console.error('获取标签列表失败:', response.data.msg);
    }
  } catch (error) {
    console.error('获取标签列表请求出错:', error);
  }
};

// 为问题添加标签
const addTagsToQuestion = async (questionId: number): Promise<boolean> => {
  if (selectedTags.value.length === 0) {
    return true; // 如果没有选择标签，直接返回成功
  }

  try {
    const response = await axios.request({
      method: 'POST',
      url: 'http://localhost:8089/question/insertQuestionTag',
      headers: {
        token: token,
        Accept: '*/*',
        'Content-Type': 'application/json'
      },
      data: {
        question_id: questionId,
        tag_id: selectedTags.value
      }
    });

    if (response.data.code === 1) {
      console.log('添加标签成功:', response.data.msg);
      return true;
    } else {
      console.error('添加标签失败:', response.data.msg);
      return false;
    }
  } catch (error) {
    console.error('添加标签请求出错:', error);
    return false;
  }
};

// 提交问题
const submitQuestion = async (): Promise<void> => {
  try {
    if (!title.value || !content.value) {
      ElMessage.warning('请填写问题标题和内容');
      return;
    }

    const response = await axios.post<{
      code: number;
      msg: string;
      data: number | null;
    }>(
        'http://localhost:8089/question/insertQuestion',
        {
          title: title.value,
          content: content.value,
          img: url.value,
          user_id: userid
        },
        {
          headers: {
            token: token || '',
            'Content-Type': 'application/json',
            Accept: '*/*'
          }
        }
    );

    result.value = response.data;
    if (result.value?.code === 1 && response.data.data) {
      // 问题创建成功后，添加标签
      const questionId = response.data.data;
      const tagResult = await addTagsToQuestion(questionId);

      if (tagResult) {
        ElMessage.success('问题发布成功');
        // 清空表单
        title.value = '';
        content.value = '';
        url.value = '';
        selectedTags.value = [];
        router.push(
            '/home'
        );
      } else {
        ElMessage.warning('问题已发布，但标签添加失败');
      }
    } else {
      ElMessage.error('发布失败: ' + (result.value?.msg || '未知错误'));
    }
  } catch (error) {
    console.error('请求出错:', error);
    ElMessage.error('发布失败，请稍后重试');
  }
};

// 切换标签选择状态
const toggleTag = (tagId: number): void => {
  const index = selectedTags.value.indexOf(tagId);
  if (index === -1) {
    selectedTags.value.push(tagId);
  } else {
    selectedTags.value.splice(index, 1);
  }
};

// 组件挂载时获取标签列表
onMounted(() => {
  getTagList();
});
</script>

<template>
  <el-container>
    <HeaderComponent /> <!-- 使用 HeaderComponent -->
    <el-container>
      <el-aside width="25%" style="height: 100vh">
      </el-aside>
      <el-main class="body">
        <div class="publish-question-container">
          <h1 style="background-color: white;">发布问题</h1>
          <div class="question-form">
            <div class="form-group">
              <label>问题标题</label>
              <input type="text" placeholder="请输入问题标题" v-model="title" />
            </div>
            <div class="form-group">
              <label>问题描述</label>
              <textarea placeholder="请详细描述您的问题" v-model="content"></textarea>
            </div>
            <div class="form-group">
              <label>问题图片</label>
              <input type="text" placeholder="请输入问题图片Url" v-model="url" />
            </div>
            <div class="form-group">
              <label>问题标签</label>
              <div class="tag-container">
                <div
                  v-for="tag in tagList"
                  :key="tag.id"
                  class="tag-item"
                  :class="{ 'tag-selected': selectedTags.includes(tag.id) }"
                  @click="toggleTag(tag.id)"
                >
                  {{ tag.tagname }}
                  <el-tooltip :content="tag.content" placement="top">
                  </el-tooltip>
                </div>
                <div v-if="tagList.length === 0" class="no-tags">
                  加载标签中...
                </div>
              </div>
            </div>
            <div class="button-group">
              <button @click="submitQuestion" class="submit-btn">发布问题</button>
            </div>
          </div>
        </div>
      </el-main>
      <el-aside width="25%">
      </el-aside>
    </el-container>
  </el-container>
</template>

<style scoped>
*{
  background-color: #F9FAFA;
}
.body{
  height: 100%;
  padding: 0 20px 20px 20px;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 5px;
  background-color: white;
}

.tag-item {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  background-color: #f0f0f0;
  border-radius: 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #ddd;
}

.tag-selected {
  background-color: #2196F3;
  color: white;
  border-color: #2196F3;
}

.tag-info-icon {
  margin-left: 5px;
  font-size: 12px;
  color: #999;
  background-color: transparent;
}

.tag-selected .tag-info-icon {
  color: #fff;
}

.no-tags {
  padding: 10px;
  color: #999;
  background-color: white;
}

/* 确保其他样式保持不变 */
.publish-question-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  margin-top: 84px;
  background-color: white;
  border-radius: 8px;
}

.question-form {
  width: 100%;
  max-width: 800px;
  margin-top: 20px;
  background-color: white;
}

.form-group {
  margin-bottom: 20px;
  background-color: white;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  background-color: white;
}

input[type="text"], textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

textarea {
  min-height: 150px;
  resize: vertical;
}

.button-group {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start;
  background-color: white;
}

button {
  margin-right: 10px;
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn {
  background-color: #2196F3;
}

button:hover {
  opacity: 0.9;
}
</style>
